package com.example.treehole.ui.component

import android.icu.util.Calendar
import com.example.treehole.ui.model.CommentType
import com.example.treehole.ui.model.SnackbarManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

fun isValidEmail(email: String): Boolean {
    val emailPattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
    return Regex(emailPattern).matches(email)
}

fun passwordFilter(newText: String): String {

    val allowedCharacters = newText.filter {
        isAscii(it) && (it.isLetterOrDigit() || it in listOf(
            '!',
            '@',
            '#',
            '$',
            '%',
            '^',
            '&',
            '*'
        ))
    }
//    Log.d("Password",allowedCharacters)
    return allowedCharacters
}

fun isAscii(c: Char): Boolean {
    return c.code in 0..127
}

fun numberTransfer(num: Int): String {
    return when {
        num < 10000 -> num.toString()
        num < 100000 -> String.format(Locale.PRC, "%.1fk", num / 1000.0)
        else -> String.format(Locale.PRC, "%.1fw", num / 10000.0)
    }
}

// 计算时间
fun formatTime(
    postTime: Long,
    isDetail: Boolean = false
): String {
    val curTime = System.currentTimeMillis()
    val timeDifference = curTime - postTime
    val oneDayMills = 24 * 60 * 60 * 1000
    val curYear = Calendar.getInstance().get(Calendar.YEAR)
    val postYear = Calendar.getInstance().apply { timeInMillis = postTime }.get(Calendar.YEAR)

    return when {
        timeDifference < 1000 -> "刚刚"
        timeDifference < 60 * 1000 -> "${timeDifference / 1000}秒前"
        timeDifference < 60 * 60 * 1000 -> "${timeDifference / (60 * 1000)}分钟前"
        timeDifference < oneDayMills -> "${timeDifference / (60 * 60 * 1000)}小时前"
        curYear == postYear -> {
            if (isDetail)
                SimpleDateFormat("MM/dd hh:mm", Locale.getDefault()).format(Date(postTime))
            else
                SimpleDateFormat("MM/dd", Locale.getDefault()).format(Date(postTime))
        }

        else -> {
            if (isDetail)
                SimpleDateFormat("yyyy/MM/dd hh:mm", Locale.getDefault()).format(Date(postTime))
            else
                SimpleDateFormat("yyyy/MM/dd", Locale.getDefault()).format(Date(postTime))
        }
    }
}

// 登录页面的提示框
fun showLoginSnackbar(message: String) {
    CoroutineScope(Dispatchers.Main).launch {
        SnackbarManager.loginSnackbarHostState.showSnackbar(message)
    }
//    Log.d("Snackbar",message)
}

// 应用页面的提示框
fun showTreeholeSnackbar(message: String) {
    CoroutineScope(Dispatchers.Main).launch {
        SnackbarManager.treeholeSnackbarHostState.showSnackbar(message)
    }
//    Log.d("Snackbar",message)
}

// 数字转成评论类型（枚举类型）
fun Int.toCommentType(): CommentType? {
    return CommentType.entries.getOrNull(this)
}
